package com.xmh.datasource.demo.interceptor;

import com.alibaba.fastjson.JSON;
import com.xmh.datasource.demo.config.DataSourceProperties;
import com.xmh.datasource.demo.content.SqlDataSourceContextHolder;
import com.xmh.datasource.demo.vo.DataSourceConfigVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
public class DataSourceSwichInterceptor implements HandlerInterceptor {

    private final DataSourceProperties dataSourceProperties;

    public DataSourceSwichInterceptor(DataSourceProperties dataSourceProperties) {
        this.dataSourceProperties = dataSourceProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String host = request.getHeader("referral");
        log.info("current host name: {}", host);

        for (Map.Entry<String, Map<String, Object>> entry : this.dataSourceProperties.getMapping().entrySet()) {
            String toJSONString = JSON.toJSONString(entry.getValue());

            DataSourceConfigVo dataSourceConfigVo = JSON.parseObject(toJSONString, DataSourceConfigVo.class);
            if (dataSourceConfigVo.getRoutingName().equalsIgnoreCase(host)) {
                SqlDataSourceContextHolder.set(dataSourceConfigVo.getRoutingName());
                break;
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SqlDataSourceContextHolder.clear();
    }
}
